package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.ExtendArticlesMapper;
import org.linlinjava.litemall.db.dao.LitemallArticlesMapper;
import org.linlinjava.litemall.db.domain.LitemallArticles;
import org.linlinjava.litemall.db.domain.LitemallArticlesExample;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class PiccArticlesService {
    @Resource
    LitemallArticlesMapper litemallArticlesMapper;

    @Resource
    ExtendArticlesMapper extendArticlesMapper;

    public LitemallArticles findById(int id){
        return litemallArticlesMapper.selectByPrimaryKey(id);
    }

    public void create(LitemallArticles record){
        litemallArticlesMapper.insertSelective(record);
    }

    /**
     * 获取所有文章记录和storage资源的联合查询（需要storage表中的headerUrl和type，且是没有被逻辑删除的
     * @param page
     * @param limit
     * @param sort
     * @return
     */
    public List<LitemallArticles> getAllArticles(Integer deleted, Integer page, Integer limit, String sort){
//        PageHelper.startPage(page, limit);
         List <LitemallArticles> mList = extendArticlesMapper.selectPartByDeleted(deleted, sort);
        Iterator<LitemallArticles> iterator = mList.iterator();

        LitemallArticles article = null;
        String detailUrl;
        while(iterator.hasNext()){
            article = iterator.next();
            detailUrl = article.getDetailUrl();
            if (detailUrl.startsWith("https://picc-admin.oss-cn-beijing.aliyuncs.com")){
                String tempStr = detailUrl.replace("https://picc-admin.oss-cn-beijing.aliyuncs.com",
                        "https://icar.oss.fanshou.site");
                article.setDetailUrl(tempStr);
            }
        }
        return mList;
    }

    public int count() {
        LitemallArticlesExample example = new LitemallArticlesExample();
        return (int) litemallArticlesMapper.countByExample(example);
    }

    public void delete(int id){
        litemallArticlesMapper.deleteByPrimaryKey(id);
        return;
    }
}
